package net.cyue.web.easyquery.provider.http.router.solon;

import net.cyue.web.easyquery.core.http.HTTPStatus;
import net.cyue.web.easyquery.core.http.adapter.AbstractHTTPResponse;
import net.cyue.web.easyquery.core.util.JSONUtil;
import org.noear.solon.core.handle.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.OutputStream;

public class SolonHTTPResponse extends AbstractHTTPResponse<Context> {

    private final Logger logger = LoggerFactory.getLogger(this.toString());

    public SolonHTTPResponse(Context response)
    {
        super(response);
    }

    @Override
    public void status(HTTPStatus status) {
        this.response.status(status.code());
    }

    @Override
    public void putHeader(String name, String value) {
        if (this.response.header(name) == null) {
            this.response.headerAdd(name, value);
        } else {
            this.response.headerSet(name, value);
        }
    }

    @Override
    public void removeHeader(String name) {
        this.response.headerSet(name, "");
    }

    @Override
    public void redirect(HTTPStatus status, String url) {
        this.response.redirect(url, status.code());
    }

    @Override
    public void redirect(String url) {
        this.response.redirect(url);
    }

    @Override
    public void end(String s) {
        this.response.output(s);
        try {
            OutputStream outputStream = this.response.outputStream();
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            this.logger.error(e.getMessage());
        }
    }

    @Override
    public void send(String body) {
        this.response.outputAsJson(body);
    }

    @Override
    public void send(Object body) {
        String json = JSONUtil.toJSONString(body);
        this.response.outputAsJson(json);
    }

    @Override
    public void write(String s) {
        this.response.output(s);
    }
}
